//
//  ShaiXuanTableViewCell.m
//  YaoHeAPP
//
//  Created by 杨亚森 on 16/7/4.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ShaiXuanTableViewCell.h"
#import "ShaiXuanTiaoJianCommonModel.h"
#import "RegionButton.h"

#define FontOfSize 12.0f
#define kMarkWidth SCREEN_WIDTH-20
#define kHuiBaiBackgroundColor RGBCOLOR(244, 244, 244)
#define kJuHuangBackgroundColor RGBCOLOR(251, 87, 60)


@interface ShaiXuanTableViewCell() {
    CGFloat _markHeight;                // 计算出来的最后一个标签的最大的Y，也就是整个markBackgroundView的高度
    int _firstTime;
}

@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIView *markBackgroundView;                   // 标签背景View
@property (nonatomic, strong) RegionButton *selectedButton;                 // 选中的按钮（适用于单选模式）
@property (nonatomic, strong) NSMutableSet *selectedButtonSet;              // 选中的按钮数组（适用于多选模式）
@property (nonatomic, strong) RegionButton *duoXuanBuXianButton;            // 记住一个特例的按钮
@property (nonatomic, strong) UIView *lineView;                             // 下划线
@property (nonatomic, strong) NSMutableArray *suozaishiAllButtonArray;      // 所在市cell所有的button

@end

@implementation ShaiXuanTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.clipsToBounds = YES;
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 80, 25)];
        titleLabel.font = Font(14);
        titleLabel.textColor = [UIColor blackColor];
        [self.contentView addSubview:titleLabel];
        self.titleLabel = titleLabel;
        
        UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        moreButton.titleLabel.font = Font(12);
        [moreButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [moreButton setTitle:@"展开" forState:UIControlStateNormal];
        [moreButton setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
        [moreButton setTitle:@"收起" forState:UIControlStateSelected];
        moreButton.frame = CGRectMake(SCREEN_WIDTH-45, titleLabel.top, 35, 25);
        moreButton.hidden = YES;
        [moreButton addTarget:self action:@selector(moreButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:moreButton];
        self.moreButton = moreButton;
        
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = RGBCOLOR(230, 232, 241);
        lineView.frame = CGRectMake(0, self.height-1, SCREEN_WIDTH, 1);
        lineView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [self.contentView addSubview:lineView];
        self.lineView = lineView;
        
        self.selectedButtonSet = [NSMutableSet set];
        self.suozaishiAllButtonArray = [NSMutableArray array];
        _firstTime = 0;
    }
    return self;
}

- (void)moreButtonClick {
    if (self.moreButton.selected == YES) {
        if (self.shouQiReloadIndexPathCellBlock) {
            self.shouQiReloadIndexPathCellBlock();
        }
    } else {
        if (self.zhanKaiReloadIndexPathCellBlock) {
            self.zhanKaiReloadIndexPathCellBlock();
        }
    }
}

- (void)setModelDictionary:(NSDictionary *)modelDictionary {
    _modelDictionary = modelDictionary;
    
    NSString *keyString = modelDictionary.allKeys.lastObject;
    self.titleLabel.text = keyString;
    
    CGFloat cellTrueHeight = [self getCellHeightWithShaiXuanTiaoJianCommonModelDictionary:modelDictionary];
    if (cellTrueHeight > kShaiXuanTableViewCellHeight+2) {
        self.moreButton.hidden = NO;
    } else {
        self.moreButton.hidden = YES;
    }
    
    if (_markBackgroundView) {
        [_markBackgroundView removeFromSuperview];
        _markBackgroundView = nil;
    }
    NSArray *shaixuanArray = modelDictionary.allValues.lastObject;
    if (shaixuanArray == nil || shaixuanArray.count == 0) return;
    _markBackgroundView = [[UIView alloc] init];
    [self fillDataWithModelArray:shaixuanArray intoView:_markBackgroundView];
    [_markBackgroundView setFrame:CGRectMake(0, _titleLabel.bottom+5, SCREEN_WIDTH, _markHeight)];
    [self.contentView addSubview:_markBackgroundView];
}

- (void)fillDataWithModelArray:(NSArray *)tempArray intoView:(UIView *)view {
    // 自定义一些宽高
    CGFloat marginLeft = 10;                            // 左边距
    CGFloat marginRight = 10;                           // 右边距
    CGFloat marginTop = 3;                              // 头间距
    CGFloat marginBottom = 10;                          // 下间距
    CGFloat spacing = 20;                               // 左右间距
    CGFloat buttonWidth;                                // 按钮宽度
    CGFloat buttonHeight = 20;                          // 按钮高度 默认25
    CGFloat howLong = marginLeft;                       // 计算中会用到，存储每行总长度，赋值给按钮X值
    CGFloat howHeight = marginTop;                      // 计算中会用到，存储每行总高度，赋值给按钮Y值
    
    ShaiXuanTiaoJianCommonModel *shaiXuanTiaoJianCommonModel;
    for (NSInteger i = 0; i < tempArray.count; i++) {
        shaiXuanTiaoJianCommonModel = (ShaiXuanTiaoJianCommonModel *)[tempArray objectAtIndex:i];
        CGSize buttonSize = [shaiXuanTiaoJianCommonModel.CONDITION_NAME sizeWithAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"HelveticaNeue" size:FontOfSize]}];
        buttonWidth = buttonSize.width+23;
        
        RegionButton *selectionButton = [RegionButton buttonWithType:UIButtonTypeCustom];
        selectionButton.titleLabel.font = [UIFont systemFontOfSize:FontOfSize];
        selectionButton.layer.borderWidth = 0.5;
        selectionButton.layer.borderColor = RGBACOLOR(221, 221, 221, 1).CGColor;
        selectionButton.layer.cornerRadius = 10.0f;
        selectionButton.layer.masksToBounds = YES;
        selectionButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        
        // 设置title
        [selectionButton setTitle:[NSString stringWithFormat:@"%@", shaiXuanTiaoJianCommonModel.CONDITION_NAME] forState:UIControlStateNormal];
        [selectionButton setTitleColor:RGBCOLOR(83, 83, 83) forState:UIControlStateNormal];
        [selectionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        selectionButton.shaiXuanTiaoJianCommonModel = shaiXuanTiaoJianCommonModel;
        [selectionButton addTarget:self action:@selector(chooseThisAction:) forControlEvents:UIControlEventTouchUpInside];
        if (self.selectionMode == radio) {
            if (self.yiXuanValue == nil) {
                if (i == 0 && ![shaiXuanTiaoJianCommonModel.CONDITION_NAME isEqualToString:@"特惠"]) {
                    selectionButton.backgroundColor = kJuHuangBackgroundColor;
                    selectionButton.selected = YES;
                    self.selectedButton = selectionButton;
                } else {
                    selectionButton.backgroundColor = kHuiBaiBackgroundColor;
                    selectionButton.selected = NO;
                }
            } else {
                if ([self.yiXuanValue isEqualToString:selectionButton.shaiXuanTiaoJianCommonModel.CONDITION_VALUE]) {
                    selectionButton.backgroundColor = kJuHuangBackgroundColor;
                    selectionButton.selected = YES;
                    self.selectedButton = selectionButton;
                } else {
                    selectionButton.backgroundColor = kHuiBaiBackgroundColor;
                    selectionButton.selected = NO;
                }
            }
        } else {
            [self.suozaishiAllButtonArray addObject:selectionButton];
            if (self.multipleChoiceYiXuanValue == nil) {
                if (self.huaNanContainCityArray.count > 0) {
                    if ([self.huaNanContainCityArray containsObject:shaiXuanTiaoJianCommonModel.CONDITION_NAME]) {
                        selectionButton.backgroundColor = kJuHuangBackgroundColor;
                        selectionButton.selected = YES;
                        [self.selectedButtonSet addObject:selectionButton.shaiXuanTiaoJianCommonModel.CONDITION_VALUE];
                    } else {
                        if ([selectionButton.shaiXuanTiaoJianCommonModel.CONDITION_NAME isEqualToString:@"不限"]) {
                            self.selectedButton = selectionButton;
                        }
                        selectionButton.backgroundColor = kHuiBaiBackgroundColor;
                        selectionButton.selected = NO;
                    }
                } else {
                    if (i == 0) {
                        selectionButton.backgroundColor = kJuHuangBackgroundColor;
                        selectionButton.selected = YES;
                        self.selectedButton = selectionButton;
                    } else {
                        selectionButton.backgroundColor = kHuiBaiBackgroundColor;
                        selectionButton.selected = NO;
                    }
                }
            } else {
                NSArray *yixuanButtonArray = [self.multipleChoiceYiXuanValue componentsSeparatedByString:@","];
                if ([yixuanButtonArray containsObject:shaiXuanTiaoJianCommonModel.CONDITION_VALUE]) {
                    selectionButton.backgroundColor = kJuHuangBackgroundColor;
                    selectionButton.selected = YES;
                    [self.selectedButtonSet addObject:selectionButton.shaiXuanTiaoJianCommonModel.CONDITION_VALUE];
                } else {
                    if ([selectionButton.shaiXuanTiaoJianCommonModel.CONDITION_NAME isEqualToString:@"不限"]) {
                        self.selectedButton = selectionButton;
                    }
                    selectionButton.backgroundColor = kHuiBaiBackgroundColor;
                    selectionButton.selected = NO;
                }
            }
        }
    
        // 计算Frame
        if (howLong + buttonWidth + marginRight <= kMarkWidth) {
            selectionButton.frame = CGRectMake(howLong+5, howHeight, buttonWidth, buttonHeight+5);
            howLong = howLong + buttonWidth + spacing;
        } else {
            howLong = marginLeft;
            howHeight = howHeight + buttonHeight + marginTop + marginBottom;
            selectionButton.frame = CGRectMake(howLong+5, howHeight, buttonWidth, buttonHeight+5);
            howLong = howLong + buttonWidth + spacing;
        }
        [view addSubview:selectionButton];
        
        CGRect tempFrame = self.markBackgroundView.frame;
        tempFrame.size.height = CGRectGetMaxY(selectionButton.frame);
        _markHeight = CGRectGetMaxY(selectionButton.frame);
        self.markBackgroundView.frame = tempFrame;
    }
}

- (CGFloat)getCellHeightWithShaiXuanTiaoJianCommonModelDictionary:(NSDictionary *)shaiXuanTiaoJianCommonModelDictionary {
    CGFloat cellHeight = 35;
    
    if (_markBackgroundView) {
        [_markBackgroundView removeFromSuperview];
    }
    // 计算markBackgroundView高度
    NSArray *shaixuanArray = shaiXuanTiaoJianCommonModelDictionary.allValues.lastObject;
    if (shaixuanArray == nil || shaixuanArray.count == 0) return cellHeight;
    _markBackgroundView = [[UIView alloc] init];
    [self fillDataWithModelArray:shaixuanArray intoView:_markBackgroundView];
    cellHeight += _markHeight+10;                       // markBackgroundView高度+底部10间距

    return cellHeight;
}

- (void)chooseThisAction:(id)sender {
    RegionButton *regionButton = (RegionButton *)sender;
    if (self.selectionMode == radio) {
        if (self.selectedButton == regionButton) return;
        self.selectedButton.selected = NO;
        self.selectedButton.backgroundColor = kHuiBaiBackgroundColor;
        regionButton.selected = YES;
        regionButton.backgroundColor = kJuHuangBackgroundColor;
        self.selectedButton = regionButton;
        
        NSString *conditionValueString = regionButton.shaiXuanTiaoJianCommonModel.CONDITION_VALUE;
        if (self.radioSelectButtonClickBlock) {
            self.radioSelectButtonClickBlock(_modelDictionary.allKeys.lastObject, conditionValueString);
        }
    } else {
        if ([regionButton.shaiXuanTiaoJianCommonModel.CONDITION_NAME isEqualToString:@"不限"]) {
            regionButton.selected = YES;
            regionButton.backgroundColor = kJuHuangBackgroundColor;
            for (RegionButton *regionButton in self.suozaishiAllButtonArray) {
                if (![regionButton.shaiXuanTiaoJianCommonModel.CONDITION_NAME isEqualToString:@"不限"]) {
                    regionButton.selected = NO;
                    regionButton.backgroundColor = kHuiBaiBackgroundColor;
                }
            }
            [self.selectedButtonSet removeAllObjects];
        } else {
            if ([self.selectedButtonSet containsObject:regionButton.shaiXuanTiaoJianCommonModel.CONDITION_VALUE]) {
                regionButton.selected = NO;
                regionButton.backgroundColor = kHuiBaiBackgroundColor;
                [self.selectedButtonSet removeObject:regionButton.shaiXuanTiaoJianCommonModel.CONDITION_VALUE];
            } else {
                self.selectedButton.selected = NO;
                self.selectedButton.backgroundColor = kHuiBaiBackgroundColor;
                regionButton.selected = YES;
                regionButton.backgroundColor = kJuHuangBackgroundColor;
                [self.selectedButtonSet addObject:regionButton.shaiXuanTiaoJianCommonModel.CONDITION_VALUE];
            }
        }
        if (self.multipleChoiceSelectButtonClickBlock) {
            if (self.selectedButtonSet.count > 0) {
                NSMutableString *mutableString = [NSMutableString string];
                NSArray *setAllObjectsArray = self.selectedButtonSet.allObjects;
                for (int i = 0; i < setAllObjectsArray.count; i++) {
                    NSString *tempRegionButonString = setAllObjectsArray[i];
                    if (0 == i) {
                        [mutableString appendString:tempRegionButonString];
                    } else {
                        [mutableString appendFormat:@",%@", tempRegionButonString];
                    }
                }
                self.multipleChoiceSelectButtonClickBlock(_modelDictionary.allKeys.lastObject, mutableString);
            } else {
                self.multipleChoiceSelectButtonClickBlock(_modelDictionary.allKeys.lastObject, nil);
            }
        }
    }
}

@end
